import React, { useState } from "react";
import ProForm, { ProFormText } from "@ant-design/pro-form";
import API from '@/services/ant-design-pro/music';
import { Modal, message, Image, Space } from 'antd'
import { ArrowRightOutlined } from '@ant-design/icons';
import UploadImg from '@/components/UploadImg'
import No_head from '../../../assets/image/no_head.jpg'
import m_config from '@/config/config'

const { addCarousel, updateCarousel } = API;

const CreateOrEdit = (props) => {

    const { isModalVisible, isShowModal, actionRef, setData, initData } = props;
    const [imgFile, setImgFile] = useState(undefined);
    const type = initData === undefined ? "添加" : "编辑";
    /**
     * 添加或编辑用户
     * @param {obj} params 参数
     * @returns 
     */
    const handleSubmit = async (params) => {
        let result;

        if (imgFile === undefined) {
            return message.error("您还未修改数据")
        }

        if (initData === undefined) { // 添加
            result = await addCarousel({
                carousel: {
                    ...params,
                },
                file: imgFile || null
            });
        } else { // 编辑
            result = await updateCarousel({
                carousel: {
                    ...initData,
                    ...params,
                },
                file: imgFile || null
            });
        }

        if (result.status == 'ok') {
            await setData();
            actionRef.current.reload();
            message.success(type + "成功");
        } else {
            message.error(type + '失败：' + result.data.message);
            console.log(result.data.error);
        }
        isShowModal(false);
    }

    const setImageFile = (params) => {
        setImgFile(params);
    }
    return (<Modal
        title={`${type}用户`}
        footer={false}
        visible={isModalVisible}
        onCancel={() => isShowModal(false)}
        destroyOnClose={true}>
        {

            <ProForm
                onFinish={(values) => handleSubmit(values)}
                initialValues={initData}
            >
                <Space size={12}>
                    <Image
                        height={100}
                        src={initData === undefined ? No_head : m_config.local + initData.carousel_file_src + initData.carousel_file_name}
                        onError={(e) => {
                            e.target.src = No_head;
                        }}
                    />
                    <ArrowRightOutlined />
                    <UploadImg setImgFile={(values) => setImageFile(values)} />
                </Space>
                <div></div>
            </ProForm>
        }
    </Modal>);
}

export default CreateOrEdit;